package utils

import (
	"encoding/binary"
	"encoding/json"
	"errors"
	"fmt"
	"go_chat_system/common"
	"io"
	"net"
)

// 将这些方法关联到结构体中
type Transfer struct {
	Conn net.Conn   // 连接
	Buf  [8096]byte // 存储请求与响应的数据
}

// 发送消息
func (this *Transfer) WriteData(data []byte) (err error) {
	// 发送消息长度
	//buf := make([]byte, 4)
	binary.BigEndian.PutUint32(this.Buf[:4], uint32(len(data)))
	// 先发送消息字符长度
	_, err = this.Conn.Write(this.Buf[:4])
	fmt.Printf("[Write Message length:%d]\n", len(data))

	// 发送消息
	_, err = this.Conn.Write([]byte(data))
	fmt.Printf("[Write Message:%v]\n", string(data))
	return
}

// 接收消息
func (this *Transfer) ReadData() (mess common.Message, err error) {
	//buf := make([]byte, 8096)
	// 接收消息长度
	_, err = this.Conn.Read(this.Buf[:4])
	if err == io.EOF {
		err = errors.New("ClientExit")
		return
	}
	// 消息字符长度
	length := binary.BigEndian.Uint32(this.Buf[:4])
	fmt.Printf("[Read Message length:%v]\n", length)

	// 接收消息内容，并响应
	size, err := this.Conn.Read(this.Buf[:length])
	if uint32(size) != length || err != nil {
		return
	}
	// 反序列化Message
	err = json.Unmarshal(this.Buf[:length], &mess)
	fmt.Printf("[Read Message:%v]\n", string(this.Buf[:length]))
	return
}
